package viz.model.flare.proxies
{
	import org.puremvc.as3.multicore.interfaces.IProxy;
	import org.puremvc.as3.multicore.patterns.proxy.Proxy;
	
	import viz.model.flare.data.StateItem;
	import viz.model.flare.data.StateMap;

	public class StateDataProxy extends Proxy
	{
		public static const NAME:String = "StateDataProxy";
		public static const DATA_POPULATED:String = "stateData/data/populated";
		
		private var childProxy:IProxy
		
		public function StateDataProxy( childProxy:IProxy )
		{
			super(NAME);
			initProxy(childProxy)
			
		}
		//todo:implement this
		public function get isDirty():Boolean{
			return false;
		}
		
		public function get packagelist():Array{
			return stateMap.packagelist;
		}
		
		override public function onRegister():void{
			flush();
		}
		
		override public function setData(data:Object):void{
			super.setData( data );
			if(data)update();
			sendDataPopulatedNote()
		}
		
		private function sendDataPopulatedNote():void{
			sendNotification(DATA_POPULATED, getData() );
		}
		
		public function flush():void{
			setData(new StateMap());
		}
		
		private function initProxy( childProxy:IProxy ):void{
			this.childProxy =  childProxy;
		}
		
		public function update():void{
			//todo: create an update cycle;
			childProxy.setData( data );
		}
		
		public function addState( state:Object ):void{
						
			switch(true){
				case( state is StateItem ):
					addStateVO( StateItem( state ) );
					break;
				case( state is String ):
					createState( String( state ) );
					break;
				default:
					throw new TypeError("Expecting StateVO or String");
			}
		}
		
		private function createState( fullPkg:String ):void{
			var state:StateItem = new StateItem();
			state.fullPath = fullPkg;
			addStateVO( state );
		}
		
		
		private function addStateVO( state:StateItem ):void{
			if( containsState( state ) ) return;
			if(stateMap.length == 0)state.initial = true;
			stateMap.addItem( state );
			update();
		}
		
		
		
		public function removeState( state:Object ):void{
			switch(true){
				case (state is StateItem && stateMap.contains( state )):
					stateMap.removeItemAt( stateMap.getItemIndex( StateItem(state) ) )
			}
			
		}
		//todo: compare by fullPkg
		public function containsState( state:Object ):Boolean{
			return false;
		}
		
		private function get stateMap():StateMap{
			return StateMap( data );
		}
		
		
		
	}
}